package com.example.www.Controller;

import com.example.www.Base.Result;
import com.example.www.Entity.Photo;
import com.example.www.Service.PhotoService;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
public class PhotoController {

    @Autowired
    private PhotoService photoService;

    @Value("${qiniu.accesskey}")
    private String accessKey;

    @Value("${qiniu.secretkey}")
    private String secretKey;

    @Value("${qiniu.bucketname}")
    private String bucket;

    @Value("${qiniu.url}")
    private String qiniuUrl;

    @GetMapping("/api/photolist")
    @CrossOrigin
    public Result getPhotoList(){
        return Result.photos(photoService.getPhotoList());
    }

    @GetMapping("/api/photo")
    @CrossOrigin
    public Result getPhoto(@RequestParam("id") int id){;
        return Result.photo(photoService.getPhoto(id));
    }

    @PostMapping("/api/addphoto")
    @CrossOrigin
    public Result addPhoto(@RequestParam("key") String key){
        photoService.addPhoto(key);
        return Result.OK();
    }

    @DeleteMapping("/api/deletephoto")
    @CrossOrigin
    public Result deletePhoto(@RequestParam("id") int id) {
        Photo photo = photoService.getPhoto(id);
        if(photo!=null) {
            String key = photo.getPhotolink().substring(qiniuUrl.length());
            Configuration cfg = new Configuration(Region.region0());
            Auth auth = Auth.create(accessKey, secretKey);
            BucketManager bucketManager = new BucketManager(auth, cfg);
            try {
                bucketManager.delete(bucket, key);
            } catch (QiniuException ex) {
                System.err.println(ex.code());
                System.err.println(ex.response.toString());
                return Result.internalError();
            }
            photoService.deletePhoto(id);
            return Result.OK();
        }else {
            return Result.OK();
        }
    }
}
